#!/usr/bin/env python
# encoding: utf-8
"""
messagetest.py

Created by 黄 冬 on 2007-12-14.
Copyright (c) 2007 __MyCompanyName__. All rights reserved.
"""

from twisted.internet import reactor
import unittest
import logging.config
import socket, select

log = logging.getLogger('xbaytable.tests.messagetest')
#logging.basicConfig(level=logging.ERROR)
#logging.basicConfig(level=logging.INFO)
logging.basicConfig(level=logging.DEBUG)

from xbaytable.conf import *
from xbaytable.utils.tableclient import *
from xbaytable.utils.tablemsg import *

class TestClientProtocol(TableClientProtocol):
    """这是测试的Protocol，在认证完后，就是发包包"""
    def AuthOK(self):
        """向服务器发出set请求"""
        while (self.sendsetcount < self.sendnum):
            if (len(self.sendwin)<TABLE_WIN_MAX):
                self.sendsetcount += 1
                msg = 'abc'
                #for i in range(1,100):
                #    msg +='********************************************************************************************************'
                #sequence_id = self.process.send_table_set(self,'a%s'%self.sendsetcount,'%s%s'%(msg,self.sendsetcount))
                sequence_id = self.process.send_table_get(self,'a%s'%self.sendsetcount)
                self.sendwin.append(sequence_id)
                log.info('send now socket_win is:%s'%len(self.sendwin))
            else:
                log.debug("window is full,window siz is:%s"%len(self.sendwin))
                reactor.callLater(0,self.AuthOK)
                return

    def connectionMade(self):
        """链接建立，初始化测试数据"""
        TableClientProtocol.connectionMade(self)
        self.sendsetcount = 0
        self.sendnum = 100
        self.sendsetrep = 0

class TestClientProcess(ProcessMessage):
    """这是测试的消息处理，收包，确认发出的包都有正确的回复"""
    def process_table_set_resp(self,transport,command,sequence_id,msg):
        """处理process_table_set_resp回复"""
        status = binpack.unpackbody(command,msg)
        log.debug('rev table_set_rest is %s'%status)
        transport.sendsetrep += 1
        if (transport.sendsetrep == transport.sendnum):
            transport.transport.loseConnection()

class messagetest(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_bind_table_server(self):
        """测试连接到服务器"""
        reactor.connectTCP(TABLE_SERVER_IP, TABLE_SERVER_PORT, TableClientFactory(TestClientProtocol,TestClientProcess))
        reactor.run()
    
if __name__ == '__main__':
    unittest.main()